#pragma once
#include<iostream>
#include<string>
#include<unordered_map>
#include "Logger.hpp"

static const std::string sep=": ";//分隔符
class Dictionary
{
private:
    void LoadConf()//加载配置文件。文件在_path中
    {
        std::ifstream in(_path);//std::ifstream是 C++ 中用于从文件读取数据的类
        if(!in.is_open())
        {
            LOG(Loglevel::ERROR) << "open file error: " << _path;
            return;
        }

        std::string line;
        //std::istream& getline(std::istream& is, std::string& str, char delim);
        //作用：从输入流 is中读取字符，直到遇到分隔符 delim（默认是换行符 `），然后将这些字符存储到字符串str` 中，并丢弃分隔符。
        while (std::getline(in,line))//从in中读到line中,getline读到结尾会自动强转为false
        {
            //测试真的读完了
            LOG(Loglevel::DEBUG)<<"load dict messagef: "<<line;
            //hello： 你好
            //将字符串切割
            auto pos=line.find(sep);
            if(pos==std::string::npos)
            {
                LOG(Loglevel::WARNING)<<"format error"<<line;
                continue;
            }
            std::string word=line.substr(0,pos);//[ )
            std::string value=line.substr(pos+sizeof(sep));
            if(word.empty() || value.empty())
            {
                LOG(Loglevel::WARNING) << "format error, word or value is empty: " << line;
                continue;
            }
            _dict.insert(std::make_pair(word, value));
        }
                

        in.close();
    }
public:
    Dictionary(const std::string&path):_path(path)
    {
        LOG(Loglevel::INFO)<<"Dictionary path is "<<_path;
        LoadConf();
        //将字典加载进来
    }
    //提供翻译服务
    std::string Translate(const std::string& word,const std::string& whoip,u_int16_t whoport)
    {
         (void)whoip;
            (void)whoport;
            auto iter = _dict.find(word);
            if(iter == _dict.end())
            {
                return "unknown";
            }
            return iter->first + "->" +  iter->second;
                }
    ~Dictionary()
    {}

private:
    std::string _path;
    std::unordered_map<std::string,std::string> _dict;
};


